package com.ruoyi.canteen.controller.v1;

import com.auth0.jwt.interfaces.Claim;
import com.ruoyi.canteen.constant.CanteenConfig;
import com.ruoyi.canteen.domain.CanteenMd;
import com.ruoyi.canteen.domain.CanteenOrderAddress;
import com.ruoyi.canteen.service.ICanteenMdService;
import com.ruoyi.canteen.service.ICanteenOrderAddressService;
import com.ruoyi.canteen.utils.JwtToken;
import com.ruoyi.canteen.vo.CanteenOrderAddressVo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 档口门店管理
 * @Author Ryan
 * @Date 2021/9/8 8:12
 * @Version 1.0
 */
@RestController
@RequestMapping("/v1/md")
public class MdApiController extends BaseController {

    @Autowired
    private ICanteenMdService canteenMdService;

    @Autowired
    private ICanteenOrderAddressService canteenOrderAddressService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private CanteenConfig canteenConfig;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Value("${canteen.business.diffStaff}")
    private Boolean diffStaff;

    @Value("${canteen.business.diffSCanteen}")
    private Boolean diffSCanteen;

    /**
     * 查询门店列表
     */
    @GetMapping("/getAll")
    public TableDataInfo getAll()
    {
        CanteenMd queryMd = new CanteenMd();
        queryMd.setOpenFlag(Long.valueOf(0));
        List<CanteenMd> list = canteenMdService.selectCanteenMdList(queryMd);
        return getDataTable(list);
    }

    /**
     * 根据来访者信息（默认地址），查询开放门店列表
     */
    @GetMapping("/getAllByUser/")
    public TableDataInfo getAllByUser(String scope, String token)
    {
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            CanteenMd queryMd = new CanteenMd();
            queryMd.setOpenFlag(Long.valueOf(0));
            if(diffStaff){
                queryMd.setBusinessScope(scope);
            }
            // 查询当前微信登录用户默认地址
            List<CanteenOrderAddressVo> addrList =
                    canteenOrderAddressService.selectCanteenOrderAddressListByUserId(uid, 1);
            // 根据用户的默认地址，过滤食堂列表
            if(addrList.size() > 0){
                if(diffSCanteen){
                    // 打开食堂筛选
                    String curAddr = addrList.get(0).getAddress();
                    // 字典表
                    SysDictData queryDictData = new SysDictData();
                    queryDictData.setDictType("qr_address");
                    List<SysDictData> dicList = sysDictDataService.selectDictDataList(queryDictData);
                    for(SysDictData dictData : dicList){
                        String dictValue = dictData.getDictValue();
                        if(curAddr.contains(dictValue)){
                            // 条件门店
                            queryMd.setDeptId(Long.valueOf(dictData.getDictLabel()));
                            List<CanteenMd> queryList = canteenMdService.selectIndexCanteenMdList(queryMd);
                            return getDataTable(queryList);
                        }
                    }
                    List<CanteenMd> mdList = canteenMdService.selectIndexCanteenMdList(queryMd);
                    return getDataTable(mdList);
                }else {
                    // 未开启食堂限制，则 所有可见门店
                    List<CanteenMd> mdList = canteenMdService.selectIndexCanteenMdList(queryMd);
                    return getDataTable(mdList);
                }
            }else {
                // 登录用户没有默认地址，则
                return getDataTable(new ArrayList<>());
            }
        }else {
            if(scope.equals("2")){
                CanteenMd queryMd = new CanteenMd();
                queryMd.setOpenFlag(Long.valueOf(0));
                if(diffStaff){
                    queryMd.setBusinessScope(scope);
                }
                List<CanteenMd> mdList = canteenMdService.selectCanteenMdList(queryMd);
                return getDataTable(mdList);
            }
            return getDataTable(new ArrayList<>());
        }

    }

    /**
     * 根据来访者范围，查询开放门店列表
     */
    @GetMapping("/getAllByScope/{scope}")
    public TableDataInfo getAllByScope(@PathVariable("scope") String scope)
    {
        CanteenMd queryMd = new CanteenMd();
        queryMd.setOpenFlag(Long.valueOf(0));
        if(diffStaff){
            queryMd.setBusinessScope(scope);
        }
        List<CanteenMd> list = canteenMdService.selectCanteenMdList(queryMd);
        return getDataTable(list);
    }

    /**
     * 获取门店详细信息
     */
    @GetMapping(value = "/getDetail/{mdId}")
    public AjaxResult getDetail(@PathVariable("mdId") Long mdId)
    {
        return AjaxResult.success(canteenMdService.selectCanteenMdByMdId(mdId));
    }

    /**
     * 获取门店限额
     * @param mdId 门店ID
     * @return
     */
    @GetMapping(value = "/getLimitAmount/{mdId}")
    public AjaxResult getLimitAmount(@PathVariable("mdId") Long mdId){
        // 方案一：配置文件读取
//        String limitAmount = canteenConfig.getMdLimitAmount().get(mdId.toString()).toString();
//        if(StringUtils.isEmpty(limitAmount)){
//            // 无限额
//            return AjaxResult.success("-1");
//        }else {
//            // 有限额，不为空
//            return AjaxResult.success(limitAmount);
//        }
        List<SysDictData> limitDict = dictTypeService.selectDictDataByType("md_limit_amount");
        for(SysDictData limit : limitDict){
            if(limit.getDictLabel().equals(mdId.toString())){
                // 有限额，不为空
                return AjaxResult.success(limit.getDictValue());
            }
        }
        // 无限额
        return AjaxResult.success("-1");
    }

}
